< previous page page_147 next page >

Page 147
In the For statement, you would specify the counter variable and the starting and ending values. At the end of the loop the Next statement instructs the computer to add 1 to the counter variable and then go back to the For statement, where the counter is compared to the ending value. If the counter is larger, the loop is ended. To see exactly what happens, a For loop can be coded without using the ForNext statements, as shown in the following code:
Counter = Start_Value
Top_Of_Loop:
    If Counter <=End_Value then
        [Code Statements]
        Counter = Counter + 1
        Goto Top_Of_Loop
    End If
As you can see, the ForNext statements do a lot of work for you. In addition, by using the Step keyword you can specify the value that is added or subtracted from the counter variable. Finally, if you must exit the loop early, you can use the Exit For statement. When the loop process is completed, program processing continues at the first line of code after the Next statement.
Tip
For debugging purposes, you should always include the counter variable name in the
Next statement. This enables you to identify the ForNext relationship when several! loops are nested within each other.

The other type of counter loop is the For EachNext loop. You actually saw this loop a little earlier today, when it was used to set the BackColor properties of a text box control array. This statement enables you to use a counter loop without having to know how many elements are in the array or collection. The syntax of this statement (shown in the following code) is very similar to the first ForNext statement; however, there are a few differences:
For Each element In group
[statements]
[Exit For]
[statements]
Next [element]
In this case, you must specify a variant-defined variable as the element, and the group is either the array or the collection with which you want to work. The remaining sections of the statement are identical to the first ForNext statement.

 
< previous page page_147 next page >

If you like this book, buy it!